import { RouteLocationNormalized } from 'vue-router'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTagsViewStore = defineStore('tagsView', () => {
  const visitedViews = ref<RouteLocationNormalized[]>([])
  const cachedViews = ref<string[]>([])

  const getVisitedViews = (): RouteLocationNormalized[] => {
    return visitedViews.value as RouteLocationNormalized[]
  }

  const getCachedViews = (): string[] => {
    return cachedViews.value
  }

  const addView = (view: RouteLocationNormalized) => {
    addVisitedView(view)
    addCachedView(view)
  }

  const addCachedView = (view: RouteLocationNormalized): void => {
    const viewName = view.name as string
    if (!viewName) return
    if (cachedViews.value.includes(viewName)) return
    if (!view.meta?.noCache) {
      cachedViews.value.push(viewName)
    }
  }

  const addVisitedView = (view: RouteLocationNormalized): void => {
    if (visitedViews.value.some((v: RouteLocationNormalized) => v.path === view.path)) return
    visitedViews.value.push(
      Object.assign({}, view, {
        title: view.meta?.title || 'no-name'
      })
    )
  }
  const delView = (
    view: RouteLocationNormalized
  ): Promise<{
    visitedViews: RouteLocationNormalized[]
    cachedViews: string[]
  }> => {
    return new Promise((resolve) => {
      delVisitedView(view)
      if (!isDynamicRoute(view)) {
        delCachedView(view)
      }
      resolve({
        visitedViews: [...(visitedViews.value as RouteLocationNormalized[])],
        cachedViews: [...cachedViews.value]
      })
    })
  }

  const delVisitedView = (view: RouteLocationNormalized): Promise<RouteLocationNormalized[]> => {
    return new Promise((resolve) => {
      for (const [i, v] of visitedViews.value.entries()) {
        if (v.path === view.path) {
          visitedViews.value.splice(i, 1)
          break
        }
      }
      resolve([...(visitedViews.value as RouteLocationNormalized[])])
    })
  }
  const delCachedView = (view?: RouteLocationNormalized): Promise<string[]> => {
    let viewName = ''
    if (view) {
      viewName = view.name as string
    }
    return new Promise((resolve) => {
      const index = cachedViews.value.indexOf(viewName)
      index > -1 && cachedViews.value.splice(index, 1)
      resolve([...cachedViews.value])
    })
  }

  const updateVisitedView = (view: RouteLocationNormalized): void => {
    for (let v of visitedViews.value) {
      if (v.path === view.path) {
        v = Object.assign(v, view)
        break
      }
    }
  }

  const isDynamicRoute = (view: RouteLocationNormalized): boolean => {
    // 检查匹配的路由记录中是否有动态段
    return view.matched.some((m) => m.path.includes(':'))
  }

  return {
    visitedViews,
    cachedViews,

    getVisitedViews,
    getCachedViews,
    addView,
    addVisitedView,
    addCachedView,
    delView,
    delVisitedView,
    delCachedView,
    updateVisitedView
  }
})
